from flask import Blueprint, flash, redirect, render_template, request, url_for
from flask_login import current_user, login_required, login_user, logout_user
from werkzeug.security import check_password_hash

from app.database.models import AdminUser
from app.server.flask_app import db, login_manager

auth_bp = Blueprint(
    "auth_bp", __name__, template_folder="templates", static_folder="static"
)


@auth_bp.route("/login", methods=["GET", "POST"])
@auth_bp.route("/admin/login", methods=["GET", "POST"])
def login():
    """
    Log-in page for registered users.
    GET requests serve Log-in page.
    POST requests validate and redirect user to admin panel.
    """

    if current_user.is_authenticated:
        return redirect("/admin")

    if request.method == "POST":
        email = request.form.get("email")
        password = request.form.get("password")

        user = db.session.query(AdminUser).filter_by(email=email).first()

        if (not user) or (not check_password_hash(user.password, password)):
            flash("Please check your login details and try again.")
            return redirect(request.url)

        login_user(user)
        next_page = request.args.get("next")
        if next_page:
            return redirect(next_page)
        else:
            return redirect("/admin")

    return render_template(
        "login.html",
        page_title="Login page",
    )


@login_manager.user_loader
def load_user(user_id):
    """Check if user is logged-in upon page load."""

    if user_id is not None:
        return db.session.query(AdminUser).get(user_id)
    return None


@login_manager.unauthorized_handler
def unauthorized():
    """Redirect unauthorized users to Login page."""
    flash("Log in to view this page")
    return redirect(url_for("auth_bp.login"))


@auth_bp.route("/logout")
@login_required
def logout():
    logout_user()
    return redirect(url_for("auth_bp.login"))
